package com.cskaoyan.order.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cskaoyan.mall.commons.result.ResponseData;
import com.cskaoyan.mall.commons.result.ResponseUtil;
import com.cskaoyan.mall.constant.ShoppingRetCode;
import com.cskaoyan.mall.order.constant.OrderRetCode;
import com.cskaoyan.order.biz.TransOutboundInvoker;
import com.cskaoyan.order.biz.context.AbsTransHandlerContext;
import com.cskaoyan.order.biz.factory.OrderProcessPipelineFactory;
import com.cskaoyan.order.dto.*;
import com.cskaoyan.order.service.OrderCoreService;
import com.cskaoyan.order.service.OrderQueryService;
import com.cskaoyan.order.form.PageInfo;

import com.cskaoyan.order.utils.ExceptionProcessorUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
public class IOrderController {

    @Autowired
    OrderQueryService orderQueryService;
    @Autowired
    OrderCoreService orderCoreService;
    @Autowired
    OrderProcessPipelineFactory orderProcessPipelineFactory;
    /**
     *  create订单
     * @param request
     */

    @PostMapping("/shopping/order")
    public ResponseData createOrder(@RequestBody CreateOrderRequest request,HttpServletRequest request1) {
////TODO
//         request.setUniqueKey();

        String user_info = request1.getHeader("user_info");
        //System.out.println(token);
        Map<String, Object> map = JSON.parseObject(user_info, Map.class);
        //JSONObject jsonObject = JSON.parseObject(token);

        Integer userId = (Integer) map.get("id");
        request.setUserId(userId.longValue());
        System.out.println("/shopping/order----------- createOrder"  );
        CreateOrderResponse result = new CreateOrderResponse();
        System.out.println("createOrderrequest = " + request);
        try {
            //创建pipeline对象
            TransOutboundInvoker invoker = orderProcessPipelineFactory.build(request);

            //启动pipeline
            invoker.start(); //启动流程（pipeline来处理）

            //获取处理结果

            AbsTransHandlerContext context = invoker.getContext();

            //把处理结果转换为response
            result = (CreateOrderResponse) context.getConvert().convertCtx2Respond(context);
            System.out.println("response orderId= " + result.getOrderId());

            System.out.println(" =============== " );
            return new ResponseUtil().setData(result);
        } catch (Exception e) {
            log.error("OrderCoreServiceImpl.createOrder Occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(result, e);
            return new ResponseUtil().setErrorMsg(result.getMsg());
        }
//        return response;
    }

    /**
     * 获取当前用户的所有订单
     * @param pageInfo
     */

    @GetMapping("/shopping/order")
    public ResponseData orderList(PageInfo pageInfo, HttpServletRequest httpRequest) {
        System.out.println("/shopping/order----------- orderList"  );
        OrderListRequest request=new OrderListRequest();

//         当前用户?

        String userInfo =  httpRequest.getHeader("user_info");
        if (userInfo != null) {


            JSONObject object = JSON.parseObject(userInfo);
            String uid = object.get("id").toString();
            request.setUserId(Long.parseLong(uid));



            request.setPage(pageInfo.getPage());
            request.setSize(pageInfo.getSize());
            request.setSort(pageInfo.getSort());
            OrderListResponse result = orderQueryService.orderList(request);
            if (OrderRetCode.SUCCESS.getCode().equals(result.getCode())) {
                return new ResponseUtil().setData(result);
            }
            return new ResponseUtil().setErrorMsg(result.getMsg());
        }
        return new ResponseUtil().setErrorMsg("not login!user_info is null!");
    }
    /**
     * 查询订单明细
     * @param id
     * @return
     */
    @GetMapping("/shopping/order/{id}")
    public ResponseData orderDetail(@PathVariable(name = "id")String id) {
        System.out.println("/shopping/order/{id}----------- orderDetail"  );
        OrderDetailRequest request=new OrderDetailRequest();
        request.setOrderId(id);
//         当前用户?

        OrderDetailResponse result = orderQueryService.orderDetail(request);
        ResponseData response=new ResponseData();
        System.out.println("result = " + result);
        if (OrderRetCode.SUCCESS.getCode().equals(result.getCode())) {
//            response.setResult(result);
//             response.setCode(Integer.parseInt(OrderRetCode.SUCCESS.getCode()));
//            response.setSuccess(true);
//            response.setMessage(OrderRetCode.SUCCESS.getMessage());
            return new ResponseUtil().setData(result);
        }
//        response.setResult(result);
//        response.setSuccess(false);
//        response.setMessage(OrderRetCode.SYSTEM_ERROR.getMessage());
//        response.setCode(Integer.parseInt(OrderRetCode.SYSTEM_ERROR.getMessage()));
        return new ResponseUtil().setErrorMsg(result.getMsg());
    }
    /**
     * 取消订单
     * @param orderId
     * @return
     */
    @PostMapping("/shopping/cancelOrder")
    public ResponseData cancelOrder(@RequestBody String orderId) {
        System.out.println("/shopping/cancelOrder ----------- cancelOrder"  );
        CancelOrderRequest request=new CancelOrderRequest();
        request.setOrderId(orderId);
//         当前用户?

        CancelOrderResponse result = orderCoreService.cancelOrder(request);

        if (OrderRetCode.SUCCESS.getCode().equals(result.getCode())) {
            return new ResponseUtil().setData(null);
        }
        return new ResponseUtil().setErrorMsg(result.getMsg());
    }
    /**
     * 删除订单
     * @param id
     * @return
     */
    @RequestMapping(value = "/shopping/order/{id}",method =RequestMethod.DELETE )
    public ResponseData deleteOrder(@PathVariable(name = "id")String id) {
        DeleteOrderRequest request=new DeleteOrderRequest();
        request.setOrderId(id);

        DeleteOrderResponse result = orderCoreService.deleteOrder(request);
        if (OrderRetCode.SUCCESS.getCode().equals(result.getCode())) {
            return new ResponseUtil().setData(null);
        }
        return new ResponseUtil().setErrorMsg(result.getMsg());
    }

}
